<template>
  <div>
    <div class="user">
      <div v-if="selectedUserList">
        <div class="user-tag" v-for="(item, index) in selectedUserList" :key="index">
          <el-tag>{{item.nickname}}</el-tag>
        </div>
      </div>
      <el-button type="primary" icon="el-icon-search" @click="open = true" size="mini" ></el-button>
    </div>

    <el-dialog
      :title="'人员选择'"
      :visible.sync="open"
      :width="width || '1000px'"
      :height="height || '650px'"
      :before-close="cancel"
      append-to-body
    >
      <div class="selectBox">
        <div class="bottomBox" v-show="showSearch">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="68px"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="用户姓名" prop="nickname">
                  <el-input
                    v-model="queryParams.nickname"
                    placeholder="请输入用户姓名"
                    clearable
                    style="width: 200px"
                    size="mini"
                    @keyup.enter.native="getList"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="手机号码" prop="mobile">
                  <el-input
                    v-model="queryParams.mobile"
                    placeholder="请输入手机号码"
                    clearable
                    style="width: 200px"
                    size="mini"
                    @keyup.enter.native="getList"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item>
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="getList"
                  >搜索</el-button
                  >
                  <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                  >重置</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="topBox">
          <div class="leftBox">
            <div class="contentBox">
              <div class="leftBox_title">组织架构</div>
              <div style="padding: 4px; margin-bottom: 4px">
                <el-input
                  v-model="deptName"
                  placeholder="请输入部门名称"
                  clearable
                  size="mini"
                  prefix-icon="el-icon-search"
                >
                </el-input>
              </div>
              <div class="treeBox">
                <el-tree
                  :data="deptOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  node-key="id"
                  default-expand-all
                  highlight-current
                  @node-click="handleNodeClick"
                />
              </div>
            </div>
          </div>

          <div class="leftBox">
            <div class="contentBox">
              <div class="leftBox_title">
                人员选择
              </div>
              <div class="peopleBox">
                <div class="peopleList">
                  <el-checkbox-group
                    ref="peopleCheckBoxes"
                    v-model="checkedUserIdList"
                    @change="handleSelectedUsersChange"
                  >
                    <el-checkbox
                      v-for="(item, index) in userList"
                      :label="item.id"
                      :key="index"
                      class="peopleCard"
                    >
                      <div class="avatarBox">
                        <div style="background: #46a6ff" class="user-avatar">
                          {{
                            item.nickname.substring(0, 1) ||
                            item.username.substring(0, 1) ||
                            "User"
                          }}
                        </div>
                      </div>
                      <div class="peopleInfoBox">
                        <div class="peopleName">
                          {{ item.nickname }} ({{ item.mobile }})
                        </div>
                        <div class="peopleDept">{{ item.dept.name || "" }}</div>
                      </div>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <!-- 分页组件 -->
                <paginationSimple v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize" @pagination="getList"/>
              </div>
            </div>
          </div>
          <!-- this.checkedUsers -->
          <div class="leftBox">
            <div class="contentBox">
              <div class="leftBox_title">
                已选择人员
                <el-button
                  class="leftBox_title_do"
                  type="text"
                  size="mini"
                  @click="clearAll"
                >全部清空</el-button
                >
              </div>
              <div class="peopleBox">
                <div class="peopleList">
                  <div
                    v-for="(item, index) in selectedUserList"
                    class="peopleCard"
                    :key="index"
                  >
                    <div class="avatarBox">
                      <div style="background: #ffa502" class="user-avatar">
                        {{
                          item.nickname.substring(0, 1) ||
                          item.username.substring(0, 1) ||
                          "User"
                        }}
                      </div>
                    </div>
                    <div class="peopleInfoBox">
                      <div class="peopleName" style="margin-top: 4px">
                        {{ item.nickname }}({{ item.mobile }})
                      </div>
                      <div class="peopleDept">{{ item.dept.name || "" }}</div>
                    </div>
                    <div
                      class="peopleDeleteBtn"
                      @click="deleteUserByUserId(item.id)"
                    ></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, listUserById } from "@/api/system/user";
import { listSimpleDepts } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "SelectMultipleUser",
  components: { Treeselect },
  model: {
    prop: 'value',
    event:'changeUser'
  },
  props: {
    width: {
      type: String,
      default: "950px",
    },
    height: {
      type: String,
      default: "650px",
    },
    value: {
      type: Array
    }
  },
  computed: {},
  data() {
    return {
      loading: false,
      total: 0,
      activeName: "first",
      defaultProps: {
        children: "children",
        label: "name",
      },
      open: false,
      // 部门树选项
      deptOptions: undefined,
      deptName: "",
      showSearch: true,
      // 用户列表
      userList: [],
      // 所有用户MAP信息 key为用户ID,value为用户对象
      allUserMap: new Map(),
      // 已选择用户列表
      selectedUserList: [],
      // 已选中的用户ID列表
      checkedUserIdList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 6,
        nickname: undefined,
        mobile: undefined,
        status: "0",
        deptId: undefined,
      },
    };
  },
  created() {
    this.getDeptTree();
    this.getList();
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    "value": {
      handler(newValue, oldValue) {
        this.checkedUserIdList = [];
        if(newValue) {
          this.checkedUserIdList= this.checkedUserIdList.concat(newValue);
        }
        this.updateSelectedUserList();
      },
      immediate:true
    }
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      listUser(this.queryParams).then((response) => {
        this.userList = response.data.list;
        this.total = response.data.total;
        this.updateAllUserMap(this.userList)
      });
    },
    /** 处理选人表单点击事件 */
    handleSelectedUsersChange() {
      this.updateSelectedUserList();
    },
    /** 更新已选择人员列表 （需要修改，传入的ID不在所有人map中情况） */
    updateSelectedUserList() {
      this.selectedUserList = [];
      let userIds = [];
      this.checkedUserIdList.forEach((userId) => {
        if (this.allUserMap.has(userId)) {
          this.selectedUserList.push(this.allUserMap.get(userId));
        }else {
          if(userIds.indexOf(userId) ==  -1){
            userIds.push(userId)
          }
        }
      });
      if(userIds != undefined && userIds != null && userIds.length != 0) {
        const param = {
          ids: userIds.join()
        }
        listUserById(param).then(response => {
          this.selectedUserList = this.selectedUserList.concat(response.data);
        })
      }
    },
    /** 更新所有人map */
    updateAllUserMap(users) {
      // 如果入参中没有用户数据，直接返回
      if(users != undefined && users != null && users.size != 0) {
        users.forEach(user => {
          if (!this.allUserMap.has(user.id)) {
            // 如果所有人中没有该用户，需要添加到集合中
            this.allUserMap.set(user.id, user);
          }
        })
      }
    },
    /** 移除已选择人员 */
    deleteUserByUserId(id) {
      for (let i = 0; i < this.checkedUserIdList.length; i++) {
        const index = this.checkedUserIdList.indexOf(id);
        if (index != -1) {
          this.checkedUserIdList.splice(index, 1);
          this.updateSelectedUserList();
          break;
        }
      }
    },
    /** 清空所有已选择 */
    clearAll() {
      this.checkedUserIdList = [];
      this.updateSelectedUserList();
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      listSimpleDepts().then((response) => {
        this.deptOptions = [];
        this.deptOptions.push(...this.handleTree(response.data, "id"));
      });
    },
    /** 部门节点点击事件 */
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    /** 部门筛选 */
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.getList();
    },
    /**关闭选择人员弹窗 */
    cancel() {
      this.open = false;
    },
    /**提交表单 */
    submitForm() {
      this.$emit("changeUser", this.checkedUserIdList[0]);
      this.cancel();
    },
  },
};
</script>

<style lang="scss" scoped>
.user {
  display: flex;
  .user-tag {
    margin-right: 10px;
  }
}

.selectBox {
  width: 100%;
  min-width: 900px;
  display: flex;
  flex-direction: column;

  .topBox {
    width: 100%;
    display: flex;
    margin-top: 10px;
    .leftBox {
      width: 280px;
      height: 400px;
      margin-right: 10px;

      -webkit-box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12),
      0 0 6px 0 rgba(0, 0, 0, 0.04);
      box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
      display: flex;
      flex-direction: column;

      .leftBox_title {
        width: 100%;
        height: 40px;
        font-size: 16px;
        line-height: 40px;
        padding-left: 10px;
        background-color: #f5f5f5;
        position: relative;
        .leftBox_title_do {
          position: absolute;
          right: 16px;
          top: 8px;
        }
      }

      .contentBox {
        width: 100%;
      }
    }
  }

  .bottomBox {
    margin-top: 15px;
    width: 100%;
    height: 75px;
    // border: 1px solid #DCDFE6;
    // -webkit-box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
    // box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
    // overflow-y: auto;

    .selectPeopleList {
      width: 100%;
      display: flex;
      flex-wrap: wrap;

      .selectPeopleCard {
        width: 50px;
        height: 56px;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin: 5px 10px;
        .user-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          color: #fff;
          background: #ffa502;
          font-size: 14px;
          text-align: center;
          line-height: 40px;
        }

        .userInfo {
          width: 100%;
          display: flex;
          flex-direction: column;
          margin-left: 5px;
          margin-right: 5px;

          div:nth-child(1) {
            font-size: 14px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 100%;
            text-align: center;
          }
        }
      }
    }
  }
}

.treeBox {
  width: 100%;
  height: 320px;
  overflow-x: hidden;
  overflow-y: auto;
}

.peopleBox {
  width: 100%;
  height: 360px;
  overflow-x: hidden;
  overflow-y: auto;

  .peopleList {
    width: 100%;
    height: auto;

    .peopleCard:hover {
      background-color: #fafafa;
      transition: 0.2s;

      .peopleName {
        color: #eb6100;
      }
    }
    .peopleCard {
      width: 100%;
      height: 48px;
      border-top: solid #f5f5f5 1px;
      border-bottom: solid #f5f5f5 1px;
      padding-left: 8px;
      display: flex;
      align-items: center;
      cursor: pointer;
      transition: 0.2s;
      ::v-deep .el-checkbox__label {
        display: flex;
        align-items: center;
      }

      .avatarBox {
        width: 40px;
        height: 40px;

        .user-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          color: #fff;
          font-size: 16px;
          text-align: center;
          line-height: 40px;
          user-select: none;
        }
      }

      .peopleInfoBox {
        width: 190px;
        height: 100%;
        display: flex;
        flex-direction: column;
        padding-left: 8px;

        .peopleName {
          width: 100%;
          height: 20px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 14px;
          line-height: 20px;
        }

        .peopleDept {
          width: 100%;
          height: 20px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 12px;
          line-height: 20px;
          color: #999;
        }
      }

      .peopleDeleteBtn {
        width: 20px;
        height: 20px;
        // border-radius: 50%;
        background: url(../../assets/images/delete0.png) no-repeat;
        background-size: 100% 100%;
        transition: 0.2s;
      }

      .peopleDeleteBtn:hover {
        width: 20px;
        height: 20px;
        // border-radius: 50%;
        background: url(../../assets/images/delete1.png) no-repeat;
        background-size: 100% 100%;
        transition: 0.2s;
      }
    }
  }
}
</style>
